package android.slc.db_backup.factory.impl;

import android.slc.db_backup.constant.Command;
import android.slc.db_backup.entity.BackupDb;
import android.slc.db_backup.factory.BackupHandler;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;

import java.io.File;
import java.util.Date;
import java.util.List;

public class MySQLBackupHandler implements BackupHandler {

    @Override
    public void backup(BackupDb backupDb) {
        Log.get().info("开始执行{}的定时任务..", backupDb.toString());
        if (backupDb.isCheckLocation()) {
            File dir = new File(backupDb.getLocation());
            if (!dir.exists()) {
                Log.get().info("目录不存在，创建目录..");
                dir.mkdirs();
            }
        }
        String filePath = new File(backupDb.getLocation() + File.separator + backupDb.getDb() + DateUtil.format(new Date(), "_yyyy-MM-dd") + ".sql").getAbsolutePath();
        String command = StrUtil.trim(Command.MYSQL_COMMAND
                .replace("#{execBasePath}", StrUtil.emptyToDefault(backupDb.getExecBasePath(), ""))
                .replace("#{ip}", backupDb.getIp())
                .replace("#{port}", backupDb.getPort())
                .replace("#{username}", backupDb.getUsername())
                .replace("#{password}", backupDb.getPassword())
                .replace("#{db}", backupDb.getDb())
                .replace("#{file}", filePath));
        Log.get().info(command);
        try {
            List<String> stringList = RuntimeUtil.execForLines(command);
            CollectionUtil.forEach(stringList, new CollUtil.Consumer<String>() {
                @Override
                public void accept(String value, int index) {
                    Log.get().info(value);
                }
            });
        } catch (Exception e) {
            Log.get().error("发生异常：", e);
        }
        Log.get().info("备份结束..");

    }
}
